<template>
  <div>
    <el-upload
      class="upload-demo"
      :action="actionUrl"
      :multiple="true"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :headers="uploadHeader"
      :data="{ type: 'image' }"
    >
      <el-button size="small" type="primary">点击上传图片</el-button>
    </el-upload>
    <div class="image-preview">
      <template v-for="(url, index) in imageUrls" :key="index">
        <div>
          <img :src="imageUrl + url" class="uploaded-image" />
          <el-button @click="removeImage(index)" type="text" icon="el-icon-delete">删除</el-button>
        </div>
      </template>
    </div>
  </div>
</template>

  <script>
import { ref, computed } from 'vue'
import { ElUpload, ElButton, ElMessage } from 'element-plus'
import store from '@/store'

export default {
  components: {
    ElUpload,
    ElButton
  },
  props: {
    defaultImages: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const imageUrls = ref(props.defaultImages)
    const imageUrl = ref(import.meta.env.VITE_APP_API_BASEURL)
    const actionUrl = (import.meta.env.DEV ? '/proxy' : import.meta.env.VITE_APP_API_BASEURL) + '/unit/upload/upload'
    const uploadHeader = computed(() => {
      return {
        'A-Token': store.state.user.a_token,
        'U-Token': store.state.user.u_token
      }
    })

    const handleSuccess = (response, file, fileList) => {
      if (response && response.code === 200) {
        const imageUrl = response.data.result // 根据实际返回结构修改
        // 将上传成功的图片 URL 添加到 imageUrls 数组中
        console.log( imageUrls.value)
        imageUrls.value.push(imageUrl)
      } else {
        ElMessage.error('上传失败')
      }
    }

    const beforeUpload = (file) => {
        console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isPPT = file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      const isPDF = file.type === 'application/pdf'
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isJPG && !isPNG && !isPPT && !isPDF) {
        ElMessage.error('上传图片只能是 JPG , PNG ,PPT , PDF 格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 10MB!')
        return false
      }

      return true // 返回 true 表示允许上传
    }

    const removeImage = (index) => {
      imageUrls.value.splice(index, 1)
    }

    return {
      imageUrl,
      imageUrls,
      actionUrl,
      uploadHeader,
      handleSuccess,
      beforeUpload,
      removeImage
    }
  }
}
</script>

  <style scoped>
.upload-demo {
  border: 1px dashed #409eff;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
}

.image-preview {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
    gap: 20px;
}

.uploaded-image {
  display: block;
  width: 120px;
  height: 120px;
  max-width: 100%;
  margin-bottom: 10px;
}
</style>
